package tptecnicas.printers;

import java.util.List;
import tptecnicas.logging.MessageInfo;
import tptecnicas.printers.parser.FormatParser;

/**
 * Clase encargada de la escritura de los mensajes de log
 * en un destino especifico.
 * Implementa el patron Template Method para desacoplar 
 * cada tipo de escrituraespecifico.
 */
public abstract class Writer {
	
	protected String path;
	protected Level level;
	protected boolean paused;
	protected String outputFormat;
	
	public Writer(List<String> parameters) {
		this.path = parameters.get(0);
		this.level = new Level(parameters.get(1)); 
		this.outputFormat = parameters.get(2);
		this.unpause();
	}

	public void write(MessageInfo message) {
		String result = this.parseMessage(message);
		this.writeOnOutput(result);
	}
	
	public abstract void writeOnOutput(String result);

	public void pause() {
		this.paused = true;
	}
	
	public void unpause() {
		this.paused = false;
	}

	public String getPath() {
		return this.path;
	}
	
	public Level getLevel() {
		return this.level;
	}
	
	protected String parseMessage(MessageInfo message) {
		if (this.paused || this.level.filterMessage(message) == null) {
			return null;
		}
		return FormatParser.parse(message, this.outputFormat);
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((path == null) ? 0 : path.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Writer other = (Writer) obj;
		if (path == null) {
			if (other.getPath() != null)
				return false;
		} else if (!path.equals(other.getPath()))
			return false;
		return true;
	}

	public boolean hasLevelEnabled(String level) {
		return this.level.hasLevelEnabled(level);
	}
}
